import React, { Component } from 'react';
import oBaseLst from '../public/eslint-base.js';

// 头部
import HeaderTop from './cpt-header';
// 左一组件
import ModLeft from './cpt-modleft';
// 中间组件 badExample
import ModMid from './cpt-modemid';
// 右边组件 goodExample
import ModRight from './cpt-modright';


class Eslint extends Component {
  constructor(props) {
    super(props);
    this.state = {
      oBaseLst,
      'isClosed': 'all',
      'sltChange': 'eslint',
      'sUrlBase': 'https://cn.eslint.org/docs/rules/' 
    };
  }

  // header 交互数据
  hpHeaderHandle (oVal) {
    switch (oVal['type']){
      case 'filterLst':
        this.setState({
          'isClosed': oVal['val']
        });
      break;

      case 'toPage':
        this.props.history.push({
          pathname: oVal['val']
        });
      break;
    }
  }

  goTo(){
    let scrollToTop = window.setInterval(function() {
      let pos = window.pageYOffset;
      if ( pos > 0 ) {
        window.scrollTo( 0, pos - 20 ); // how far to scroll on each step
      } else {
        window.clearInterval( scrollToTop );
      }
    }, 2);
  }

  render() {
    const { oBaseLst, isClosed, sltChange, sUrlBase } = this.state;

    const cptModLst = [];
    Object.keys(oBaseLst).forEach((item, index) => {
      const { name, resion, description, badExample, goodExample, valid } = oBaseLst[item];
      
      // 过滤显示 all on off
      if (isClosed !== 'all' && valid.toString() !== isClosed){
        return;
      }

      let styListBox = "fx rule";
      if (valid.toString() === 'off'){
        styListBox += " rule-closed";
      }

      cptModLst.push(
        <div
          key={index.toString()}
          className={styListBox}
        >
          <ModLeft
            key={"left"+name}
            name={name}
            resion={resion}
            description={description}
            sUrlBase={sUrlBase}
            valid={valid}
          />
          
          {!!badExample && <ModMid
            key={"min"+name}
            badExample={badExample}
          />}
          
          {!!goodExample && <ModRight
            key={"right"+name}
            goodExample={goodExample}
          />}
        </div>
      );
      return;
    });

    return (
      <React.Fragment>
        <HeaderTop
          hpHeaderHandle={this.hpHeaderHandle.bind(this)}
          hpSltChange={sltChange}
        />

        <div className="fx header-box">
          <div className="left-box header-sty">规则说明</div>
          <div className="mid-box header-sty warn">错误的示例</div>
          <div className="right-box header-sty good">正确的示例</div>
        </div>

        {cptModLst}

        <div className="top" onClick={this.goTo.bind(this)}></div>
      </React.Fragment>
    );
  }
}

export default Eslint;
